<template>
  <div class="toolbar">
    <button class="btn" @click="format">格式化</button>
    <button class="btn" @click="copy">复制结果</button>
  </div>
  <div class="code-view">
    <Codemirror
      class="code-editor"
      v-model:value="code"
      :options="cmOptions"
      border
      ref="cmRef"
      height="400"
      width="600"
    >
    </Codemirror>
    <Codemirror
      class="code-editor"
      v-model:value="formatCode"
      :options="cmOptions"
      border
      ref="cmRef"
      height="400"
      width="600"
    >
    </Codemirror>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from "vue";
import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";

const code = ref(
  `
  // 示例代码
  var i = 0;
  for (; i < 9; i++) {
      console.log(i);
      // more statements
  }
  `
);

const cmRef = ref();
const cmOptions = {
  mode: "text/javascript",
};

const formatCode = ref("");

function format() {
  formatCode.value = code.value.replace(/(?:\/\/.*)|(?:\/\*[\s\S]*?\*\/)/g, "").replace(/^\s*$(?:\r?\n|\r)/gm, "");
}

onUnmounted(() => {
  cmRef.value?.destroy();
});

function copy() {
  copyToClipboard();
  alert("复制到剪切板");
}

function copyToClipboard() {
  // 创建一个临时的textarea元素
  const textarea = document.createElement('textarea');
  // 设置textarea不可见
  textarea.style.position = 'fixed';
  textarea.style.left = '-9999px';
  textarea.style.top = '-9999px';
  // 将文本赋值给textarea
  textarea.value = formatCode.value;
  // 将textarea添加到文档中
  document.body.appendChild(textarea);
  // 选中textarea中的文本
  textarea.select();
  // 执行复制操作
  const successful = document.execCommand('copy');
  // 移除textarea元素
  document.body.removeChild(textarea);
  // 返回复制操作是否成功
  return successful;
}

</script>

<style scoped>
.toolbar {
  padding: 10px;
  width: 100%;
  background-color: cornflowerblue;
} 
.btn {
  margin-left: 16px;
  background-color: crimson;
  color: white;
  padding: 8px 16px;
  outline: none;
  border: none;
  border-radius: 8px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: .1s;
}
.btn:hover {
  background-color: crimson;
  opacity: .9;
}
.btn:active {
  opacity: .3;
}
.code-view {
  display: flex;
  
}
.code-editor {
  flex: 1;
  min-height: 600px;
}
</style>